package gitee.derumin.nice_boat.mixin;

import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.vehicle.BoatEntity;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

@Mixin(BoatEntity.class)
public abstract class BoatEntityMixin extends Entity {

    @Shadow @Nullable public abstract LivingEntity getControllingPassenger();

    @Shadow private boolean pressingLeft;

    @Shadow private boolean pressingRight;

    @Shadow private boolean pressingForward;

    @Shadow private boolean pressingBack;

    public BoatEntityMixin(EntityType<?> type, World world) {
        super(type, world);
    }

    @Inject(method = "updatePaddles", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/vehicle/BoatEntity;setYaw(F)V", shift = At.Shift.AFTER))
    private void centering(CallbackInfo ci){
        if (!this.pressingLeft
                && !this.pressingRight
                && (this.pressingForward || this.pressingBack)
                && this.getControllingPassenger() != null
                && this.getControllingPassenger() instanceof PlayerEntity player){
            float angle = MathHelper.wrapDegrees(this.getYaw() - player.getYaw());
            if (angle < 22.5f && angle >= 0.01f){
                this.setYaw(this.getYaw() - (angle/20 + 0.01f));
            } else if (angle < 0.01f && angle >= -0.01f) {
                this.setYaw(this.getYaw() - angle);
            } else if (angle < -0.01f && angle > -22.5f) {
                this.setYaw(this.getYaw() - (angle/20 - 0.01f));
            }
        }
    }

    @Redirect(method = "updatePassengerPosition", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;setYaw(F)V"))
    private void keepYaw(Entity passenger, float yaw){}
}
